package com.example.demolearn.controller;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;


@RequestMapping("/uploadFile")
@RestController
public class FileUploadHandle extends HttpServlet {
    @RequestMapping("/upload")
    public void uploadFile(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
        String path = request.getSession().getServletContext().getRealPath("/data/image");
        File file = new File(path);
        if (!file.exists()&&!file.isDirectory()){
            System.out.println("当前目录不存在");
            file.mkdirs();
        }

        String message = "";
        // 使用apache 上传组件处理文件上传步骤
        // 1. 创建一个DiskFIleItemFactory工厂
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // 2.创建一个文件上传解析器
        ServletFileUpload servletFileUpload = new ServletFileUpload(factory);
        // 解决中文上传文件名的乱码
        servletFileUpload.setHeaderEncoding("UTF-8");
        // 3.判断上传文件是否是上传文件的表单
        if(!ServletFileUpload.isMultipartContent((HttpServletRequest) request)){
            return;
        }
        // 4、使用ServletFileUpload解析器解析上传数据，解析结果返回的是一个List<FileItem>集合，每一个FileItem对应一个Form表单的输入项
        List<FileItem> fileItems = null;
        try {
            fileItems = servletFileUpload.parseRequest((HttpServletRequest) request);

            for (FileItem item : fileItems){
                if (item.isFormField()){
                    String fieldName = item.getFieldName();
                    //解决普通输入项的数据的中文乱码问题
                    String s = item.getString("UTF-8");
                    String s1 = new String(fieldName.getBytes(), "UTF-8");
                    System.out.println(s + s1);
                }else{
                    //如果fileitem中封装的是上传文件，得到上传的文件名称，
                    String name = item.getName();
                    System.out.println(name);
                    if (name != null || name.trim().equals("")){
                        continue;
                    }
                    // 由于不同的浏览器提交的文件名不一致  有些是带了文件路径的  所有我们需要截取一段 只保留文件名那部分
                    String fileName = name.substring(name.lastIndexOf(File.separator) + 1);
                    // 获取文件输入流
                    InputStream inputStream = item.getInputStream();
                    // 创建一个文件输出流
                    FileOutputStream outputStream = new FileOutputStream(path + File.separator + fileName);
                    System.out.println(path + File.separator + fileName);
                    // 创建缓冲区
                    byte[] bytes = new byte[1024];
                    // 判断文件是否读取完
                    int length = 0;
                    // 循环把输入流 读入到缓冲区中, (len = in.read(buffer)> 0) 就表示 里面还有数据
                    while((length = inputStream.read())>0){
                        outputStream.write(bytes,0,length);
                    }
                    // 关闭输入流
                    inputStream.close();
                    // 关闭输出流
                    outputStream.close();
                    // 删除处理上传生成的临时文件
                    item.delete();
                    message = "文件上传成功";
                }
            }
        } catch (FileUploadException | IOException e) {
            System.out.println(e);
        }

    }
    @RequestMapping("/downLoad")
    public void downLoad(String name, HttpServletResponse response) throws Exception {
        File file = new File("logs" + name + ".logs");
        if (file.exists()) {
            throw new Exception("文件不存在");
        }
        response.setContentType("application/form-download");
        response.addHeader("Content-Disposition","attchment;filename=" + name);

        byte[] bytes = new byte[1024];
        FileInputStream fileInputStream = new FileInputStream(file);
        ServletOutputStream outputStream = response.getOutputStream();
        int i;
        while ((i = fileInputStream.read(bytes)) != -1){
            outputStream.write(bytes,0,i);
        }
    }
}
